import logging

from base_service import BaseService
from db.student_client import StudentClient
from db.survey_client import SurveyClient


class SurveyService(BaseService):
  def __init__(self, user):
    super(SurveyService, self).__init__(user)
    self.survey_client = SurveyClient()

  def getSectionAnswers(self, request):
    user_student_id = self.getStudentIdForCurrentUser()
    answers = self.survey_client.getSectionAnswers(user_student_id,
        request['section_id'])
    return {'answers': [answer.to_dict() for answer in answers]}

  def updateAnswer(self, request):
    user_student_id = self.getStudentIdForCurrentUser()
    answer_dict = request['answer']

    # If we're adding a new answer then the student_id won't be set yet, so
    # let's add it.
    if not answer_dict.has_key('student_id'):
      answer_dict['student_id'] = user_student_id

    answer = self.survey_client.answerDictToModel(answer_dict);
    
    self.authorizeAnswerChange(answer)
    self.survey_client.updateAnswer(answer)
    
    return {'answer': answer.to_dict()}

  def deleteAnswer(self, request):
    answer = self.survey_client.getAnswer(request['id'])
    if answer:
      self.authorizeAnswerChange(answer)
      self.survey_client.deleteAnswer(answer)
    return {}

  def getFriendSurveys(self, request):
    friend_surveys = self.survey_client.getFriendSurveysForStudent(
        self.getStudentIdForCurrentUser())
    return {'friend_surveys': [survey.to_dict() for survey in friend_surveys]}

  def updateFriendSurvey(self, request):
    user_student_id = self.getStudentIdForCurrentUser()
    friend_survey_dict = request['friend_survey']

    # If we're adding a new friend survey then the student_id won't be set yet,
    # so let's add it.
    if not friend_survey_dict.has_key('student_id'):
      friend_survey_dict['student_id'] = user_student_id

    friend_survey = self.survey_client.friendSurveyDictToModel(
        friend_survey_dict);

    self.authorizeFriendSurveyChange(friend_survey)
    self.survey_client.updateFriendSurvey(friend_survey)

    return {'friend_survey': friend_survey.to_dict()}

  def updateFriendSurveys(self, request):
    user_student_id = self.getStudentIdForCurrentUser()
    friend_surveys = []
    for friend_survey_dict in request['friend_surveys']:
      # If we're adding a new friend survey then the student_id won't be set
      # yet, so let's add it.
      if not friend_survey_dict.has_key('student_id'):
        friend_survey_dict['student_id'] = user_student_id

      friend_survey = self.survey_client.friendSurveyDictToModel(
          friend_survey_dict)
      self.authorizeFriendSurveyChange(friend_survey)
      friend_surveys.append(friend_survey)

    self.survey_client.updateFriendSurveys(friend_surveys)
    return {'friend_surveys': [survey.to_dict() for survey in friend_surveys]}

  def deleteFriendSurvey(self, request):
    friend_survey = self.survey_client.getFriendSurvey(request['id'])
    if friend_survey:
      self.authorizeFriendSurveyChange(friend_survey)
      self.survey_client.deleteFriendSurvey(friend_survey)
    return {}

  def getStrainedFriendSurveys(self, request):
    strained_friend_surveys = \
        self.survey_client.getStrainedFriendSurveysForStudent(
            self.getStudentIdForCurrentUser())
    return {'strained_friend_surveys':
        [survey.to_dict() for survey in strained_friend_surveys]}

  def updateStrainedFriendSurvey(self, request):
    user_student_id = self.getStudentIdForCurrentUser()
    strained_friend_survey_dict = request['strained_friend_survey']

    # If we're adding a new friend survey then the student_id won't be set yet,
    # so let's add it.
    if not strained_friend_survey_dict.has_key('student_id'):
      strained_friend_survey_dict['student_id'] = user_student_id

    strained_friend_survey = self.survey_client.strainedFriendSurveyDictToModel(
        strained_friend_survey_dict);

    self.authorizeStrainedFriendSurveyChange(strained_friend_survey)
    self.survey_client.updateStrainedFriendSurvey(strained_friend_survey)

    return {'strained_friend_survey': strained_friend_survey.to_dict()}

  def deleteStrainedFriendSurvey(self, request):
    strained_friend_survey = self.survey_client.getStrainedFriendSurvey(
        request['id'])
    if strained_friend_survey:
      self.authorizeStrainedFriendSurveyChange(strained_friend_survey)
      self.survey_client.deleteStrainedFriendSurvey(strained_friend_survey)
    return {}

  def authorizeAnswerChange(self, answer):
    authorized_student_id = self.getStudentIdForCurrentUser()
    if (not authorized_student_id or
        authorized_student_id != answer.student_id):
      raise Exception('Security violation: User trying to update an Answer ' \
          'model this isn\'t theirs.')

  def authorizeFriendSurveyChange(self, friend_survey):
    authorized_student_id = self.getStudentIdForCurrentUser()
    if (not authorized_student_id or
        authorized_student_id != friend_survey.student_id):
      raise Exception('Security violation: User trying to update a ' \
          'FriendSurvey model this isn\'t theirs.')

  def authorizeStrainedFriendSurveyChange(self, strained_friend_survey):
    authorized_student_id = self.getStudentIdForCurrentUser()
    if (not authorized_student_id or
        authorized_student_id != strained_friend_survey.student_id):
      raise Exception('Security violation: User trying to update a ' \
          'StrainedFriendSurvey model this isn\'t theirs.')
